import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import {
  getCompanyID,
  getPosIDs,
  getUserDepID,
  getUserID,
  requestFunCompon,
} from '@/utils';
import { Button, message, Spin } from 'antd';
import { Ref, useContext, useEffect, useRef } from 'react';
import { useRequest } from 'umi';
import { UserManageContext, UserOtherHandleContext } from '../hooks';
import { getUserRowByID } from '../hooks/userManageTableServices';
import { IUserSetPosDataModal } from '../type';
import { UserAddOrEditPos } from './UserAddOrEditPos';

export const UserSetPosDataModal: React.FC<IUserSetPosDataModal> = ({
  onClose, //关闭弹框
  checkRows, //是否显示modal
  posModalType, //区分是设置岗位还是批量设置岗位
  checkedRowKeys, //批量设置岗位选中的key
}) => {
  const { userFixCls, rightRoladTabieUser } = useContext(UserManageContext);
  const { userOthDispatch, twoLeftSelectKeys, twoLeftSelectRows } = useContext(
    UserOtherHandleContext,
  );

  const userSetPosRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const { userDetail, userInfoLoading } = getUserRowByID(checkRows); //获取数据详情

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (userSetPosRef) {
      if (userSetPosRef.current) {
        if (userSetPosRef.current.onModalCancel) {
          userSetPosRef.current.onModalCancel();
        }
      }
    }
  };

  useEffect(() => {
    if (userDetail && userDetail?.id) {
      handEditPOSData(userDetail);
    }
    return () => {
      userOthDispatch({
        type: 'remove-allOtherHandle-state',
      });
    };
  }, [userDetail]);

  // 处理编辑选择的岗位数据
  const handEditPOSData = (resObj: any) => {
    let posIds: any[] = [];
    let posRows: any[] = [];
    if (resObj?.id && resObj?.mpositionList?.length > 0) {
      resObj?.mpositionList?.forEach((item: any) => {
        posIds?.push(item?.id);
        posRows?.push({ ...item, textType: item?.postType });
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectKeys',
        payload: posIds,
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectRows',
        payload: posRows,
      });
    } else {
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectKeys',
        payload: [],
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectRows',
        payload: [],
      });
    }
  };

  // 设置岗位保存
  const saveSetPosition = () => {
    let params: any = {
      // id: userDetail?.id,
      userPositionID:
        twoLeftSelectKeys?.length > 0 ? twoLeftSelectKeys?.toString() : null,
      versionNum: userDetail?.versionNum,
    };
    if (twoLeftSelectKeys?.length > 0) {
      allotPosService?.run(params);
    } else {
      message.warning('请选择至少一个岗位！', 4);
    }
  };

  // 调用设置岗位接口
  const allotPosService = useRequest(
    (payload: any) => {
      let url =
        posModalType == 'SETPOS'
          ? '/userController/allotPosition'
          : posModalType == 'ALLPOS'
          ? '/userController/batchAllotPosition'
          : '';
      let methodType = 'PUT';
      let parObj: any = {
        ...payload,
      };

      if (posModalType == 'SETPOS') {
        parObj['id'] = userDetail?.id;
      } else if (posModalType == 'ALLPOS') {
        parObj['userIds'] =
          checkedRowKeys?.length > 0 ? checkedRowKeys?.toString() : null;
      }

      return requestFunCompon(methodType, url, {
        ...parObj,
        modifyerID: getUserID(),
        modifyPositionID: getPosIDs(),
        modifyDepartmentID: getUserDepID(),
        modifyCompanyID: getCompanyID(),
      });
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
          onCloseModal();
          rightRoladTabieUser();
        } else {
          message.error(res?.msg);
        }
      },
    },
  );

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={userSetPosRef}
        title={'设置用户岗位'}
        width={document.body.clientWidth * 0.5}
        onCancel={onClose}
        className={userFixCls + 'addEditModalStyle'}
        footer={
          <>
            <Button onClick={onCloseModal}>取消</Button>
            <Button
              type={'primary'}
              onMouseOut={(event: any) => {
                event?.target?.nodeName == 'BUTTON'
                  ? event?.target?.blur()
                  : event.target.parentNode.blur();
              }}
              onClick={saveSetPosition}
              loading={userInfoLoading || allotPosService?.loading}
            >
              保存
            </Button>
          </>
        }
        bodyStyle={{
          padding: '5px 10px',
          // height: window.screen.height * 0.5,
        }}
        centered
      >
        <div className={userFixCls + 'modalChildren'}>
          <Spin spinning={userInfoLoading || allotPosService?.loading}>
            {/**
             * 新增用户设置岗位用的也是这个, 注意区分
             */}
            <UserAddOrEditPos />
          </Spin>
        </div>
      </OneModal>
    </>
  );
};
